<template>
	<view class="container sponsor-sureorder">
		<view class="addr-list" @click="jump('/pages/user/addrList?type=selectAddr')">
			<view class="addr-info" v-if="addrInfo&&addrInfo.id">
				<view>
					<view class="addr-user">
						<text class="iconfont" style="font-size: 34rpx;margin-right:20rpx;">&#xe639;</text>
						<text style="font-size: 34rpx;color: #232323;margin-right:20rpx;">{{addrInfo.name}}</text>
						<text style="font-size: 30rpx;color: #8F8F8F;">{{addrInfo.phone}}</text>
					</view>
					<view class="addr-detail ">
						{{addrInfo.address}}
					</view>
				</view>
			</view>
			<view class="addr-info" v-else>
				<view class="add-addr-btn yuan-btn btn-success">暂无地址，去设置</view>
			</view>
		</view>
		<view class="goods-list">
			<view class="list-content">
				<image class="list-bg" :src="$resFileUrl+detailInfo.image" mode="widthFix"></image>
				<view class="list-title">{{detailInfo.introduce}}</view>
			</view>
			<view class="list-bottom">
				<text class="seed-price-unit">售价：</text>
				<text class="seed-price c-danger">{{detailInfo.price}}元</text>
				<view class="num-box">
					<text class="iconfont" @click="minusNum">&#xe711;</text>
					<input class="num-input" type="number" v-model="formData.num">
					<text class="iconfont" @click="addNum">&#xe607;</text>
				</view>
			</view>
		</view>
		<view class="page-bottom">
			<view class="bottom-left">
				<view class="total-box">
					<text>实付款：</text>
					<text class="total-price-unit">￥</text>
					<text class="total-price">{{$toDecimalStr(detailInfo.price*formData.num)}}</text>
				</view>
			</view>
			<view class="bottom-right yuan-btn btn-success" @click="clickSure">提交订单</view>
		</view>
	</view>
</template>

<script setup lang="ts">
	import { onMounted, reactive, ref } from 'vue';
	import commonStore from '@/store/commonStore';
	import { onShow, onLoad } from '@dcloudio/uni-app'
	import { getStorage, hideLoading, showLoading, showToast } from '../../common/util';
	import api from '../../common/api';
	const addrInfo = ref<any>({})
	const detailInfo = ref<any>({})
	const formData = reactive({
		num: 1
	})
	let pageId = ''
	let preNum = 1
	onLoad((options) => {
		pageId = options.id;
		preNum = options.num
	})
	onMounted(async () => {
		formData.num = preNum
		getDetail()

	})
	onShow(() => {
		getAddrInfo()
	})
	const getDetail = async () => {
		showLoading()
		try {
			const res = await api.getAdoptById(pageId)
			detailInfo.value = res.data || []
		} finally {
			hideLoading()
		}

	}
	const getAddrInfo = () => {
		//如果store 有数据 取store数据，如果没有，去默认地址
		const storeAddr = commonStore.state.selAddr
		if (storeAddr && storeAddr.id) {
			addrInfo.value = storeAddr
		} else {
			getDefAddr()
		}
	}
	const getDefAddr = async () => {
		showLoading()
		try {
			const res = await api.getAddrList()
			const data = res.data
			addrInfo.value = data.find(item => {
				return item.defaultFlag === '2'
			})
		} finally {
			hideLoading()
		}
	}
	const minusNum = () => {
		--formData.num
	}
	const addNum = () => {
		++formData.num
	}
	const jump = (url : string) => {
		uni.navigateTo({ url: url })
	}
	const clickSure = async () => {
		showLoading()
		try {
			if (!addrInfo.value || !addrInfo.value.id) {
				showToast('请先选择地址')
				return
			}
			const res = await api.addSponsor({
				adoptId: pageId,
				count: formData.num,
				addressId: addrInfo.value.id
			})

			// 调起支付
			const payRes = await api.getPayRes({
				"totalFee": 0.01,//res.data.totalFee,
				"serialNumber": res.data.serialNumber,
				"openid": res.data.openid
			})
			doPay({...payRes.data,orderId:res.data.adoptRecord.id})
			// showToast('保存成功')
			// uni.navigateBack()
		} finally {
			hideLoading()
		}
	}
	const doPay = (payData) => {
		wx.requestPayment({
			timeStamp: payData.timeStamp + '',
			nonceStr: payData.nonceStr,
			package: payData.package,
			signType: 'RSA',
			paySign: payData.paySign,
			success(res) {
				doPaySuccess(payData)
			},
			fail(res) {
				console.info(res)
			}
		})

	}
	const doPaySuccess = async (payData : any) => {
		payNum = 0
		// 多次查询后台支付是否成功
		showLoading({ title: '支付结果查询中，请稍后' })
		getPayStatus(payData)
	}
	let payNum = 0
	const getPayStatus = async (payData : any) => {
		payNum++
		const res = await api.getAdoptRecordById({ id:payData.orderId})
		if (res.data.status === '2') {
			//支付成功
			hideLoading()
			showToast('支付成功',{},()=>{
				uni.redirectTo({
					url: '/pages/user/mySponsor'
				})
			})
			
		} else {
			if (payNum >= 5) {
				hideLoading()
				showToast('支付结果查询失败，请联系客服或刷新界面查看结果',{},()=>{
					uni.redirectTo({
						url: '/pages/user/mySponsor'
					})
				})
				
			} else {
				setTimeout(() => {
					getPayStatus(payData)
				}, 1000)
			}
		}
	}
</script>

<style lang="scss">
	.sponsor-sureorder {
		padding: 30rpx;

		.addr-list {
			background-color: #fff;
			box-shadow: 0 8rpx 10rpx 0 rgba(0, 0, 0, 0.1);
			border-radius: 12rpx;
			padding: 20rpx;
			margin-bottom: 20rpx;
		}

		.addr-user {
			display: flex;
			align-items: center;
		}

		.addr-info {
			display: flex;
			align-items: center;
			justify-content: space-between;

			.iconfont {
				flex-shrink: 0;
			}
		}

		.addr-detail {
			font-size: 30rpx;
			color: #8F8F8F;
			margin-top: 15rpx;
		}

		.goods-list {
			background-color: #fff;
			box-shadow: 0 8rpx 10rpx 0 rgba(0, 0, 0, 0.1);
			border-radius: 12rpx;
			padding: 20rpx;
			margin-bottom: 20rpx;
		}

		.list-content {
			display: flex;
			padding-bottom: 20rpx;
			border-bottom: solid 1px #eee;
		}

		.list-title {
			padding-top: 20rpx;
			font-size: 34rpx;
			color: #232323;
		}

		.list-bg {
			width: 200rpx;
			height: 200rpx;
			margin-right: 30rpx;
		}

		.list-bottom {
			display: flex;
			align-items: center;
			margin-top: 15rpx;
			padding-top: 15rpx;
		}

		.num-box {
			display: flex;
			align-items: center;

			.iconfont {
				font-size: 30rpx;
				color: #D8D8D8;
				padding: 10rpx 0;
			}
		}

		.num-input {
			border: solid 1px #8F8F8F;
			width: 60rpx;
			padding: 4rpx 0;
			font-size: 30rpx;
			font-weight: bold;
			margin: 0 20rpx;
			text-align: center;
			border-radius: 4rpx;
		}

		.seed-price-unit {
			font-size: 28rpx;
			color: #8F8F8F;
		}

		.seed-price {
			flex-grow: 1;
			font-size: 30rpx;
			font-weight: bold;
			color: #FF5F56;
		}

		.page-bottom {
			position: fixed;
			bottom: 0;
			left: 0;
			width: 100%;
			height: 120rpx;
			background: #FFFFFF;
			box-shadow: 0 0 20rpx 0 rgba(0, 0, 0, 0.1);
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 0 20rpx;
		}

		.bottom-right {
			width: 170rpx;
			height: 66rpx;
			border-radius: 66rpx;
		}

		.total-price-unit {
			font-size: 24rpx;
			color: #FF5F56;
		}

		.total-price {
			font-size: 30rpx;
			flex-grow: 1;
			color: #FF5F56;
		}

		.add-addr-btn {
			display: inline-flex;
			height: 80rpx;
			border-radius: 80rpx;
			width: 300rpx;
			margin: 30rpx auto;
		}
	}
</style>